/**     
* @Title: UserServiceImpl.java
* @Package me.springboot.security.service.impl 
* @Description: TODO
* @author weiwei 
* @date 2017/08/29
* @version V1.0     
*/
package me.springboot.security.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import me.springboot.core.AbstractService;
import me.springboot.security.dao.UserMapper;
import me.springboot.security.model.Role;
import me.springboot.security.model.User;
import me.springboot.security.service.RoleService;
import me.springboot.security.service.UserService;
import me.springboot.security.userdetails.MyUserDetails;
import tk.mybatis.mapper.entity.Condition;

/**
 * @ClassName: UserService
 * @Description: TODO
 * @author weiwei
 * @date 2017/08/29
 */
@Service
@Transactional
public class UserServiceImpl extends AbstractService<User> implements UserService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private RoleService roleService;

	@Override
	public User findByUsername(String username) {
		if (StringUtils.isNotBlank(username)) {
			Condition condition = new Condition(me.springboot.security.model.User.class);
			condition.createCriteria().andEqualTo("username", username);
			condition.createCriteria().andEqualTo("enabled", User.ENABLED_YES);
			List<User> users = findByCondition(condition);
			if (!CollectionUtils.isEmpty(users)) {
				return users.get(0);
			}
		}
		return null;
	}

	@Override
	public MyUserDetails queryByUsername(String username) {
		User user = findByUsername(username);
		return getUserInfo(user);
	}

	private MyUserDetails getUserInfo(User user) {
		if (null != user) {
			MyUserDetails userDetails = new MyUserDetails();
			userDetails.setId(user.getId());
			userDetails.setEmail(user.getEmail());
			userDetails.setPassword(user.getPassword());
			userDetails.setUsername(user.getUsername());
			Role role = roleService.findByUserId(user.getId());
			if (null != role) {
				userDetails.setRole(role);
				userDetails.setRoleId(role.getId());
				userDetails.setRoleName(role.getName());
			}
			return userDetails;
		}
		return null;
	}

	@Override
	public MyUserDetails queryById(Integer id) {
		if (null != id) {
			return getUserInfo(findById(id));
		}
		return null;
	}

}